﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}

<link href="~/css/site.css" rel="stylesheet" />
<link href="~/layui/css/layui.css" rel="stylesheet" />

<div class="layui-container" style="padding:20px">
    <div class="layui-row">
        <div class="layui-col-md12">
            <h2>修改客户信息</h2>
        </div>
    </div>
    <div class="layui-row">
        <div class="layui-col-md8 layui-col-md-offset2">
            <form class="layui-form" id="UpdateClient">
                <div class="layui-form-item">
                    <label class="layui-form-label">客户编号</label>
                    <div class="layui-input-block">
                        <input type="text" name="ClientCode" placeholder="客户编号" autocomplete="off" class="layui-input" readonly>
                    </div>
                </div>
                
                <div class="layui-form-item">
                    <label class="layui-form-label">客户名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="ClientName" lay-verify="required" placeholder="请输入客户名称" autocomplete="off" class="layui-input">
                    </div>
                </div>
                
                <div class="layui-form-item">
                    <label class="layui-form-label">客户类型</label>
                    <div class="layui-input-block">
                        <select name="CTypeId" lay-verify="required" lay-search>
                            <option value="">请选择客户类型</option>
                        </select>
                    </div>
                </div>
                
                <div class="layui-form-item">
                    <label class="layui-form-label">联系人</label>
                    <div class="layui-input-block">
                        <input type="text" name="ClientContact" lay-verify="required" placeholder="请输入联系人姓名" autocomplete="off" class="layui-input">
                    </div>
                </div>
                
                <div class="layui-form-item">
                    <label class="layui-form-label">状态</label>
                    <div class="layui-input-block">
                        <input type="radio" name="ClientState" value="true" title="启用">
                        <input type="radio" name="ClientState" value="false" title="禁用">
                    </div>
                </div>
                
                <div class="layui-form-item">
                    <label class="layui-form-label">手机号</label>
                    <div class="layui-input-block">
                        <input type="tel" name="ClientTel" lay-verify="required|phone" placeholder="请输入手机号码" autocomplete="off" class="layui-input">
                    </div>
                </div>
                
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">备注</label>
                    <div class="layui-input-block">
                        <textarea name="ClientRemark" placeholder="请输入备注信息" class="layui-textarea" rows="3"></textarea>
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="UpdateClient"><i class="layui-icon layui-icon-ok"></i> 保存</button>
                        <button type="button" class="layui-btn layui-btn-primary" id="backToList"><i class="layui-icon layui-icon-left"></i> 返回列表</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 先引入jQuery，再引入其他脚本 -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="~/js/site.js"></script>
<script src="~/layui/layui.js"></script>
<script>
    // 页面加载：从本地缓存读取id并反填（与开票修改页一致的风格）
    $(function(){
        var clientId = localStorage.getItem("clientId");
        if (clientId) {
            loadClientInfo(clientId);
        }
    })

    // 加载客户类型
    function loadCTypes(selectedId){
        $.ajax({
            url: 'http://localhost:5054/api/Client/GetCType',
            type: 'GET',
            dataType: 'json',
            success: function(res){
                var select = $('select[name="CTypeId"]');
                select.find('option:not(:first)').remove();
                if(res && res.code === 200 && res.data){
                    $(res.data).each(function(){
                        if(!this.isDel){
                            select.append('<option value="' + this.cTypeId + '">' + this.cTypeName + '</option>');
                        }
                    });
                }
                if(selectedId){
                    select.val(String(selectedId));
                }
                layui.form.render('select');
            }
        })
    }

    // 根据id加载详情
    function loadClientInfo(clientId){
        $.ajax({
            url: 'http://localhost:5054/api/Client/FanTianClien?ClientId=' + clientId,
            type: 'GET',
            dataType: 'json',
            success: function(res){
                if(res && (res.code === 200 || res.Code === 200) && res.data){
                    var d = res.data;
                    // 若后端返回数组，取第一个（参考开票修改页的写法）
                    if (Array.isArray(d) && d.length > 0) {
                        d = d[0];
                    }
                    // 兼容不同大小写的字段
                    var clientCode  = d.clientCode  || d.ClientCode  || '';
                    var clientName  = d.clientName  || d.ClientName  || '';
                    var clientTel   = d.clientTel   || d.ClientTel   || '';
                    var clientRemark= d.clientRemark|| d.ClientRemark|| '';
                    var clientContact = d.clientContact || d.ClientContact || '';
                    var clientState = (d.clientState !== undefined ? d.clientState : d.ClientState);
                    var typeId = d.cTypeId || d.CTypeId || d.ctypeId || d.TypeId;

                    $('input[name="ClientCode"]').val(clientCode);
                    $('input[name="ClientName"]').val(clientName);
                    $('input[name="ClientContact"]').val(clientContact);
                    $('input[name="ClientTel"]').val(clientTel);
                    $('textarea[name="ClientRemark"]').val(clientRemark);
                    if(clientState === true || clientState === 'true' || clientState === 1 || clientState === '1'){
                        $('input[name="ClientState"][value="true"]').prop('checked', true);
                    }else{
                        $('input[name="ClientState"][value="false"]').prop('checked', true);
                    }
                    loadCTypes(typeId);
                    layui.form.render();
                }else{
                    layer.msg('加载客户信息失败');
                }
            },
            error: function(){
                layer.msg('网络错误，无法加载客户信息');
            }
        })
    }

    layui.use(['form','layer'], function(){
        var form = layui.form;
        var layer = layui.layer;

        $('#backToList').click(function(){
            window.location.href = '/Client/Show';
        });

        form.on('submit(UpdateClient)', function(data){
            var f = data.field;
            var id = localStorage.getItem("clientId");
            $.ajax({
                url: 'http://localhost:5054/api/Client/UpdateClinent',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    clientId: parseInt(id),
                    clientCode: f.ClientCode,
                    clientName: f.ClientName,
                    cTypeId: parseInt(f.CTypeId),
                    clientContact: f.ClientContact,
                    clientState: f.ClientState === 'true',
                    clientTel: f.ClientTel,
                    clientRemark: f.ClientRemark || ''
                }),
                success: function(res){
                    if(res && res.code === 200){
                        layer.msg('客户信息修改成功！', {icon:1}, function(){
                            window.location.href = '/Client/Show';
                        });
                    }else{
                        layer.msg('客户信息修改失败');
                    }
                },
                error: function(){
                    layer.msg('网络错误，请稍后重试');
                }
            })
            return false;
        });
    })
</script>